<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">新增</el-button>

    <el-table v-loading="listLoading" :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="编号" width="80">
        <template slot-scope="scope">
          {{ scope.row.DocEntry }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户组编号" width="320">
        <template slot-scope="scope">
          {{ scope.row.Code }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户组名称" width="320">
        <template slot-scope="scope">
          {{ scope.row.Name }}
        </template>
      </el-table-column>
      <el-table-column v-if="false" align="header-center" label="权限明细" width="300">
        <template slot-scope="scope">
          {{ scope.row.U_Menu }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">Edit</el-button>
  <!--        <el-button type="danger" size="small" @click="handleDelete(scope)">Delete</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit Role':'New Role'">
      <el-form :model="role" label-width="80px" label-position="left">
        <el-form-item label="组编码">
          <el-input v-model="role.Code" placeholder="请输入用户组编码" :disabled="dialogType == 'edit'" />
        </el-form-item>
        <el-form-item label="组名称">
          <el-input
            v-model="role.Name"
            placeholder="请输入用户组名称"
          />
        </el-form-item>
        <el-form-item label="权限">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="key"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { fetchBOUSGs, updateBOUSGs } from '@/api/res'
import Pagination from '@/components/Pagination'
import path from 'path'
import { deepClone, getUserRoutes } from '@/utils'
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
import store from '@/store'
import { getUserInfo } from '@/utils/auth'

const defaultRole = {
  key: '',
  name: '',
  routes: [],
  Code:'',
  Name:'',
  U_Menu:'',
  DocEntry:''
}

export default {
  name: 'UsrgroupList',
  components: { Pagination },
  data() {
    return {
      list: null,
      flist: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getRoutes()
    //this.getRoles()

    // updateBOUSGs({ Code:'G1', Name:'组1', U_Menu:"{\"role\":[\"A1\",\"B1\",\"C1\",\"C2\",\"C3\",\"D3\",\"E1\",\"E2\",\"E3\",\"F1\",\"F2\",\"F3\"]}"}).then(res=>{
    //   console.log('updateBOUSGs-----ok:',res)
    // }).catch(err=>{
    //   console.log('updateBOUSGs-----err:',err)
    // })
    this.getList()
    console.log('getUserInfo----',getUserInfo())
    store.dispatch("permission/getUserRoutes").then(res=>{
      console.log('Store-getUserRoutes---',res)
    })
  },
  methods: {
    getList() {
      this.listLoading = true

      fetchBOUSGs(this.listQuery).then(res=>{
        const { flist, curPageList} = res
        console.log('fetchBOUSGs--------',res)
         this.flist = flist
         this.rolesList = curPageList
         this.total = flist.length

         this.listLoading = false

      }).catch(err=>{
        console.log('error submit!!',err);
        this.listLoading = false
      })

    },

      async getRoutes() {
        const res = await getRoutes()
        this.serviceRoutes = res.data
        this.routes = this.generateRoutes(res.data)
      },
      async getRoles() {
        const res = await getRoles()
        this.rolesList = res.data
      },

      // Reshape the routes structure so that it looks the same as the sidebar
      generateRoutes(routes, basePath = '/') {
        const res = []

        for (let route of routes) {
          // skip some route
          //if (route.hidden) { continue }
          if (route.constant) { continue }

          const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

          if (route.children && onlyOneShowingChild && !route.alwaysShow) {
            route = onlyOneShowingChild
          }

          const data = {
            path: path.resolve(basePath, route.path),
            title: route.meta && route.meta.title,
            key: route.key
          }

          // recursive child routes
          if (route.children) {
            data.children = this.generateRoutes(route.children, data.path)
          }
          res.push(data)
        }
        return res
      },
      generateArr(routes) {
        let data = []
        routes.forEach(route => {
          data.push(route)
          if (route.children) {
            const temp = this.generateArr(route.children)
            if (temp.length > 0) {
              data = [...data, ...temp]
            }
          }
        })
        return data
      },
      handleAddRole() {
        this.role = Object.assign({}, defaultRole)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = 'new'
        this.dialogVisible = true
      },
      handleEdit(scope) {
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.checkStrictly = true

        this.role = deepClone(scope.row)
        const uMenu = JSON.parse(scope.row.U_Menu)
        console.log('handleEdit--routes----',scope.row,uMenu.role)
        this.role.routes = getUserRoutes(uMenu.role)
        this.$nextTick(() => {
          const routes = this.generateRoutes(this.role.routes)
          console.log('handleEdit------', this.role,routes)
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))
          this.checkStrictly = false
        })
      },
      handleDelete({ $index, row }) {
        this.$confirm('Confirm to remove the role?', 'Warning', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        })
          .then(async() => {
            await deleteRole(row.key)
            this.rolesList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed!'
            })
          })
          .catch(err => { console.error(err) })
      },
      generateTree(routes, basePath = '/', checkedKeys) {
        const res = []

        for (const route of routes) {
          const routePath = path.resolve(basePath, route.path)

          // recursive child routes
          if (route.children) {
            route.children = this.generateTree(route.children, routePath, checkedKeys)
          }

          if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
            res.push(route)
          }
        }
        return res
      },
      async confirmRole() {
        const isEdit = this.dialogType === 'edit'
        const checkedKeys = this.$refs.tree.getCheckedKeys().filter(v=>v.length>1)
        console.log('confirmRole--0----',this.routesData,checkedKeys)
        this.role.U_Menu = JSON.stringify({'role':checkedKeys})
        this.role.routes = getUserRoutes(checkedKeys)
        console.log('confirmRole--2----',this.role,getUserRoutes(checkedKeys))

        if (isEdit) {
          updateBOUSGs(this.role).then(res=>{
            console.log('updateBOUSGs-----ok:',res)
          }).catch(err=>{
            console.log('updateBOUSGs-----err:',err)
          })
          for (let index = 0; index < this.rolesList.length; index++) {
            if (this.rolesList[index].Code === this.role.Code) {
              console.log('confirmRole--3----',this.rolesList[index])
              this.rolesList.splice(index, 1, Object.assign({}, this.role))
              console.log('confirmRole--4----',this.rolesList[index])
              break
            }
          }
        } else {
          updateBOUSGs(this.role).then(res=>{
            console.log('updateBOUSGs----new-ok:',res)
            this.getList()
            //this.rolesList.push(this.role)
          }).catch(err=>{
            console.log('updateBOUSGs----new-err:',err)
          })
        }

        const { Code, Name } = this.role
        this.dialogVisible = false
        this.$notify({
          title: 'Success',
          dangerouslyUseHTMLString: true,
          message: `
              <div>Role Code: ${Code}</div>
              <div>Role Name: ${Name}</div>
            `,
          type: 'success'
        })
      },
      // reference: src/view/layout/components/Sidebar/SidebarItem.vue
      onlyOneShowingChild(children = [], parent) {
        let onlyOneChild = null
        //const showingChildren = children.filter(item => !item.hidden)
        const showingChildren = children
        // When there is only one child route, the child route is displayed by default
        if (showingChildren.length === 1) {
          onlyOneChild = showingChildren[0]
          onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
          return onlyOneChild
        }

        // Show parent if there are no child route to display
        if (showingChildren.length === 0) {
          onlyOneChild = { ... parent, path: '', noShowingChildren: true }
          return onlyOneChild
        }

        return false
      }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
